package org.web.ssm.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.io.ResolverUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by LUOLIANG on 2016/6/3.
 */
public class HttpClientUtils {

    public static String doGetStr(String url) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        String result = "";
        try {
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet);
            //获取Response对象的Entity
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity, "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String doPostStr(String url, String outstr) throws IOException {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(url);
        String result = "";

        httpPost.setEntity(new StringEntity(outstr, "utf-8"));
        HttpResponse httpResponse = closeableHttpClient.execute(httpPost);
        result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");

        return result;
    }
}
